﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace Knowledgecast.Twitter.WPF.App
{
    /// <summary>
    /// Interaction logic for FriendsTimeline.xaml
    /// </summary>
    public partial class FriendsTimeline : UserControl, ITimelinePanel
    {
        DispatcherTimer timer;

        public FriendsTimeline()
        {
            InitializeComponent();
            timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 5, 0);            
        }

        public TwitterApi Twitter { get; set; }
        public TimelineMode Mode { get; set; }
        public string PanelTitle { get; set; }

        void timer_Tick(object sender, EventArgs e)
        {
            Load();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtTitle.Text = PanelTitle;
            Twitter.GetFriendsTimelineCompleted += new Knowledgecast.Twitter.UpdateStatusDelegate(Twitter_GetStatusCompleted);
            Twitter.GetRepliesCompleted += new Knowledgecast.Twitter.UpdateStatusDelegate(Twitter_GetStatusCompleted);
            timer.Start();
            Load();
        }        

        private void Load()
        {
            LoadFriendsTimeline();
        }

        private void LoadFriendsTimeline()
        {
            try
            {
                if (Mode == TimelineMode.Friends)
                {
                    Twitter.GetFriendsTimelineAsync();
                }
                else if (Mode == TimelineMode.Replies)
                {
                    Twitter.GetRepliesAsync();
                }
            }
            catch (Exception ex)
            {
                Debug("Load crashed: " + ex.Message + ": " + ex.StackTrace);
            }
        }

        void Twitter_GetStatusCompleted(ObservableCollection<Status> statuses)
        {
            if (statuses.Count > 0)
            {
                Dispatcher.Invoke(new UpdateStatusDelegate(UpdateStatuses), new object[] { statuses });
            }
        }

        #region ITimelinePanel Members

        public event CloseRequestedDelegate CloseRequested;

        #endregion

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            if (CloseRequested != null)
            {
                CloseRequested(this);
            }
        }

        void UpdateStatuses(ObservableCollection<Status> statuses)
        {
            if (itmsFriendsTimeline.ItemsSource == null)
            {
                itmsFriendsTimeline.ItemsSource = statuses;
            }
            else
            {
                ObservableCollection<Status> existingStatuses = itmsFriendsTimeline.ItemsSource as ObservableCollection<Status>;

                while (existingStatuses.Count > 20 - statuses.Count)
                {
                    existingStatuses.RemoveAt(existingStatuses.Count - 1);
                }

                foreach (Status s in statuses)
                {
                    existingStatuses.Insert(0, s);
                }

                //This should force a rebind of the itemscontrol. Need to do this so that the times update
                itmsFriendsTimeline.ItemsSource = new ObservableCollection<Status>(existingStatuses);
            }
        }

        void Debug(string message)
        {
            string debugMessage = "[" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + "] - " + PanelTitle;
            debugMessage += ": " + message;
            Trace.WriteLine(debugMessage);
        }
    }

    public delegate void UpdateStatusDelegate(ObservableCollection<Status> statuses);

    public enum TimelineMode
    {
        Blank = 0,
        Friends,
        Replies
    }
}
